package com.dream.classinfo;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.wzsdk.login.Landing;
import com.example.wzsdk.login.LoginState;
import com.example.wzsdk.scan.Search;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/9/8.
 */

public class SDKManager implements LoginState, Search.SearchFish, AdapterView.OnItemClickListener {

    private Context context;
    private int loginCount=0;
    private Landing landing;
    private Timer weizoneTimer;
    private Message message;
    private boolean weizone_live;
    private onGetData onGetData;
    private Search search;
    private List<String> ipList;
    private ProgressDialog progressDialog;
    private AlertDialog.Builder builder;
    private AlertDialog alertDialog;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    private static final int MSG=0;
    private static final int SHOW_IP=1;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG:
                    Toast.makeText(context,msg.obj.toString(),Toast.LENGTH_SHORT).show();
                    break;
                case SHOW_IP:
                    showIP();
                    break;
            }
        }
    };

    public SDKManager(Context context) {
        this.context=context;
        init();
    }
//***************************************初始化***************************************
    public void setSdkDataListener(onGetData onGetData){
        this.onGetData=onGetData;
    }

    private void init(){
        sharedPreferences=context.getSharedPreferences("appinfo",Context.MODE_PRIVATE);
        editor=sharedPreferences.edit();
        progressDialog=new ProgressDialog(context);
        progressDialog.setMessage("搜索中...");
        builder=new AlertDialog.Builder(context);
        search=new Search(getAPPID());
    }

    public void initLanding(){
        landing=new Landing(getAPPID());
        landing.setLoginState(this);
    }

//***************************************搜索主机***************************************
    public void initSearch(){
        progressDialog.show();
        search.EngSearch(context);
        search.setSearchFish(this);
    }

    @Override
    public void SearchFishWifi(List<String[]> list) {

    }

    @Override
    public void SearchFishWna(List<String[]> list) {
        progressDialog.dismiss();
        if (list==null||list.size()==0){
            senToast("未搜索到主机");
            return;
        }
        ipList=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ipList.add(list.get(i)[0]);
        }
        handler.sendEmptyMessage(SHOW_IP);
    }

    private void showIP(){
        ListView listView=new ListView(context);
        listView.setAdapter(new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,ipList));
        listView.setOnItemClickListener(this);
        builder.setView(listView);
        alertDialog=builder.show();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        alertDialog.dismiss();
        onGetData.onSearchFinish(ipList.get(position));
    }

//***************************************登录主机***************************************
    public void landingSDK(){
        weizoneTimer=new Timer();
        weizoneTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (!weizone_live) {
                    loginCount++;
                    weiZoneStart();
                }
            }
        },1000,getSdkReConn());
    }

    //启动SDK登录
    private void weiZoneStart(){
        senToast("尝试第"+(loginCount)+"次登录");
        String weizonIp=getWeizonIp();
        if (!weizonIp.equals("")){
            landing.Login(weizonIp,5800);
        }
    }

    //回调接口
    public interface onGetData{
        void onSearchFinish(String weiZoneIp);
        void getLandState(boolean isLand);
        void getDevData(String UIID, String VALUE, String RFID, String INDEX, String DEVID, String HOST);
    }

    @Override
    public void LoginStatus(boolean b, String s) {
        if (b){
            weizone_live=true;
            loginCount=0;
            onGetData.getLandState(b);
            senToast("登录成功");
        }else {
            senToast("退出登录/登录失败");
            weizone_live=false;
            return;
        }
    }

    @Override
    public void AttentionStarting(String s, byte b, String s1, String s2, String s3) {
        onGetData.getDevData(s,b+"",null,s1,s2,s3);
    }

    @Override
    public void AttentionProcess(String s, byte b, String s1, String s2, String s3, String s4) {
        onGetData.getDevData(s,b+"",s1,s2,s3,s4);
    }

    @Override
    public void SetVarState(String s, byte b, String s1) {

    }

//***************************************SDK操作***************************************

    //获取设备列表
    public List<String[]> getDevList(){
        List<String[]> devList = landing.getDateList();
        for (int i = 0; i < devList.size(); i++) {
            System.out.println(Arrays.toString(devList.get(i)));
        }
        return landing.getDateList();
    }
    //SDK关注变量
    public void attentionVariable(String UIID){
        landing.atnVariable(UIID);
    }
    public void attenionDev(String UIID){
        landing.atnDevice(UIID);
    }
    //取消关注变量
    public void cancelAttentionVariable(String UIID){
        landing.canVariable(UIID);
    }
    //取消关注设备
    public void cancelAttentionDev(String UIID){
        landing.canDevice(UIID);
    }
    //SDK控制设备
    public void ControlDev(String UIID,String devState){
        landing.setVariable(UIID,devState);
    }
    public void ControlDev(String UIID,String devId,String devState){
        landing.setVariable(UIID,devId,devState);
    }

    //SDK发送键值
    public void senKey(String UIID,int key){
        landing.setKeyVariable(UIID,key);
    }
    public void senKey(String UIID,String devId,int key){
        landing.setKeyVariable(UIID,devId,key);
    }

    //关闭所有连接
    public void closeAllConn(){
        landing.canAllcon();
    }

//***************************************GET/SET***************************************
    //SDK重连时间
    public void setSdkReConn(int sdkReConn){
        editor.putInt("sdkReConn",sdkReConn).commit();
    }
    public int getSdkReConn(){
        return sharedPreferences.getInt("sdkReConn",10000);
    }

    //主机IP
    public void setWeizonIp(String weizonIp){
        editor.putString("weizonIp",weizonIp).commit();
    }
    public String getWeizonIp(){
        return sharedPreferences.getString("weizonIp","");
    }

    //登录状态
    public boolean getLandingSate(){return weizone_live;};

//***************************************辅助方法***************************************

    //首次运行执行，得到APPID并保存到本地
    public String getAPPID() {
        if (!sharedPreferences.getBoolean("isFirst",false)){
            String base = "abcdefghijklmnopqrstuvwxyz0123456789";
            Random random = new Random();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < 8; i++) {
                int number = random.nextInt(base.length());
                sb.append(base.charAt(number));
            }
            editor.putString("appid",sb.toString());
            editor.putBoolean("isFirst",true);
            editor.commit();
            return sb.toString();
        }else{
            return  sharedPreferences.getString("appid","default");
        }
    }

    //发送消息
    private void senToast(String error){
        message=new Message();
        message.what=MSG;
        message.obj=error;
        handler.sendMessage(message);
    }

    public void exit(){
        if (weizoneTimer!=null){weizoneTimer.cancel();};
        if (landing!=null){landing.exitLogin();};
    }
}
